var baseUrl = $('base').attr('href');
var url = baseUrl + 'upd/',
        uploadButton = $('<button/>')
            .addClass('btn_laranja')
            .prop('disabled', true)
            .text('Processando...')
            .on('click', function () {
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .text('Abortar')
                    .on('click', function () {
                        $this.remove();
                        data.abort();
                    });
                data.submit().always(function () {
                    $this.remove();
                });
            });
    $('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        autoUpload: false,
        acceptFileTypes: /(\.|\/)(zip)$/i,
        maxFileSize: 5000000, 
    }).on('fileuploadadd', function (e, data) {
        data.context = $('<div/>').appendTo('#files');
        $.each(data.files, function (index, file) {
            var node = $('<p/>')
                    .append($('<span/>').text('Atualizar a partir do arquivo "'+file.name+'".'));
            if (!index) {
                node
                    .append('<br>')
                    .append(uploadButton.clone(true).data(data));
            }
            node.appendTo(data.context);
        });
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,
            file = data.files[index],
            node = $(data.context.children()[index]);
        if (file.preview) {
            node
                .prepend('<br>')
                .prepend(file.preview);
        }
        if (file.error) {
            node
                .append('<br>')
                .append(file.error);
        }
        if (index + 1 === data.files.length) {
            data.context.find('button')
                .text('Iniciar atualização')
                .prop('disabled', !!data.files.error);
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
		$('#progress .bar').animate({ width: '33%'}, 1200);
        /*$('#progress .bar').css(
            'width',
            progress + '%'
        );*/
    }).on('fileuploaddone', function (e, data) {
		$(".fileinput-button").fadeOut("slow");		
		$("#files").html('Atualizando sistema');
		$.ajax(baseUrl + 'upd/upd.php?acao=atualizar').done(function(data){
			if(data == 1){
				$('#progress .bar').animate({ width: '66%'}, 1200);
				$("#files").html('Atualizando a versão do banco de dados');
				$("#files").load(baseUrl + 'upd/upd.php?acao=atualizarbd',function(data){
					$('#progress .bar').animate({ width: '100%'}, 1200);	
				});				
			}else{
				$("#files").html('Erro! Contate o administrador do sistema.');	
			}
		});
    }).on('fileuploadfail', function (e, data) {
        $.each(data.result.files, function (index, file) {
            var error = $('<span/>').text(file.error);
            $(data.context.children()[index])
                .append('<br>')
                .append(error);
        });
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');